import React, { useState, useEffect } from 'react';
import { Box, Typography, Grid, Card, CardContent, Divider, Chip } from '@mui/material';
import { Dashboard as DashboardIcon, Shield, Warning, BarChart, DirectionsCar, Group, LocationOn } from '@mui/icons-material';
import { apiRequest } from '../utils/api';
import VehicleDataChart from '../components/VehicleDataChart';
import EmergencyAlert from '../components/EmergencyAlert';

const Dashboard = () => {
  const [userData, setUserData] = useState(null);
  const [vehicleSummary, setVehicleSummary] = useState({ total: 0, active: 0, warning: 0 });
  const [alertSummary, setAlertSummary] = useState({ total: 0, active: 0, resolved: 0 });
  const [vehicleDataList, setVehicleDataList] = useState([]);
  const [alertData, setAlertData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const loadDashboardData = async () => {
      try {
        setLoading(true);
        
        // 检查localStorage中是否有token
        const token = localStorage.getItem('token');
        console.log('Current token in localStorage:', token ? token.substring(0, 20) + '...' : 'No token');
        
        // 首先尝试通过API请求获取真实用户信息
        try {
          // 请求获取当前用户信息
          const userResponse = await apiRequest.get('/api/auth/me');
          const userData = userResponse.data;
          setUserData(userData);
          localStorage.setItem('userInfo', JSON.stringify(userData));
          console.log('Successfully loaded user info from API:', userData.email);
          
          // 获取车辆汇总信息
          const vehicleDataResponse = await apiRequest.get('/api/vehicle-data');
          console.log('Vehicle data response:', vehicleDataResponse.data);

          const vehicleDataList = vehicleDataResponse.data;
          
          // 从车辆数据中提取车辆ID列表
          const vehicleIds = [...new Set(vehicleDataList.map(data => data.vehicleId))];
          
          // 根据车辆的紧急标志计算汇总信息
          const activeVehicles = vehicleDataList.filter(data => !data.emergencyFlag).length;
          const warningVehicles = vehicleDataList.filter(data => data.emergencyFlag).length;
          
          setVehicleSummary({
            total: vehicleIds.length,
            active: activeVehicles,
            warning: warningVehicles
          });
          
          // 保存车辆数据到状态，供后续使用
          setVehicleDataList(vehicleDataList);
          
          // 从车辆数据中提取警报信息
          const alerts = vehicleDataList.filter(data => 
            data.emergencyFlag === true
          ).map(data => ({
            id: data.id,
            type: '紧急情况',
            severity: 'high',
            status: 'ACTIVE',
            time: data.timestamp,
            vehicleId: data.vehicleId
          }));
          
          const activeAlerts = alerts.length;
          const resolvedAlerts = 0; // 在当前实现中没有已解决的警报
          
          setAlertSummary({
            total: alerts.length,
            active: activeAlerts,
            resolved: resolvedAlerts
          });
          
          // 保存警报数据到状态
          setAlertData(alerts);
        } catch (apiError) {
          console.warn('Failed to get user info from API:', apiError.response?.status || 'Unknown error');
          console.log('API Error details:', apiError);
          
          // 处理特定的错误状态
          if (apiError.response?.status === 401) {
            console.error('Unauthorized access - token might be invalid or expired');
            // 清除无效token
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            // 重定向到登录页
            window.location.href = '/login';
            return;
          }
          
          if (apiError.response?.status === 404) {
            console.error('User not found - invalid email or user does not exist');
            setError('用户不存在');
            return;
          }
          
          // 尝试从localStorage获取用户信息作为后备方案
          let savedUserInfo = localStorage.getItem('userInfo');
          
          if (savedUserInfo) {
            try {
              const userInfo = JSON.parse(savedUserInfo);
              setUserData(userInfo);
              console.log('Successfully loaded user info from localStorage:', userInfo.email);
            } catch (parseError) {
              console.error('Failed to parse user info from localStorage:', parseError);
              setError('无法加载用户信息');
            }
          } else {
            setError('没有找到用户信息，请先登录');
          }
        }
        
        setError(null);
      } catch (err) {
        console.error('Dashboard data load error:', err);
        console.error('Error details:', err.response?.status, err.response?.data);
        
        // 尝试从localStorage获取用户信息
        const savedUserInfo = localStorage.getItem('userInfo');
        if (savedUserInfo) {
          try {
            const userInfo = JSON.parse(savedUserInfo);
            setUserData(userInfo);
            console.log('Loaded user info from localStorage after API error:', userInfo.email);
          } catch (parseError) {
            console.error('Failed to parse user info from localStorage:', parseError);
            setError('无法加载用户信息，请重新登录');
          }
        } else {
          setError('无法加载用户信息，请重新登录');
        }
      } finally {
        setLoading(false);
      }
    };

    loadDashboardData();
  }, []);

  const getStatCard = (title, value, icon, color) => (
    <Card sx={{ height: '100%' }}>
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="subtitle1" color="text.secondary">{title}</Typography>
          {icon}
        </Box>
        <Typography variant="h4" sx={{ color }}>{value}</Typography>
      </CardContent>
    </Card>
  );

  if (loading) {
    return (
      <Box sx={{ py: 4 }}>
        <Typography variant="h5" align="center">Loading dashboard data...</Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ py: 4 }}>
        <Typography variant="h6" color="error" align="center">{error}</Typography>
      </Box>
    );
  }

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取状态样式
  const getStatusStyle = (status) => {
    switch(status) {
      case 'normal':
        return { backgroundColor: 'success.light', color: 'success.dark' };
      case 'warning':
        return { backgroundColor: 'warning.light', color: 'warning.dark' };
      case 'error':
        return { backgroundColor: 'error.light', color: 'error.dark' };
      default:
        return { backgroundColor: 'default.light' };
    }
  };

  // 获取警报严重程度样式
  const getAlertSeverityStyle = (severity) => {
    switch(severity) {
      case 'high':
        return { color: 'error.main' };
      case 'medium':
        return { color: 'warning.main' };
      case 'low':
        return { color: 'success.main' };
      default:
        return {};
    }
  };

  // 获取用户绑定的车辆数据
  const getUserBoundVehicleData = () => {
    if (!userData) return null;
    
    try {
      // 优先使用从API获取的真实数据
      if (vehicleDataList.length > 0) {
        // 获取用户绑定的车辆ID
        let userVehicleBindings = JSON.parse(localStorage.getItem('userVehicleBindings') || '{}');
        let userVehicleId = userVehicleBindings[userData.id];
        
        // 如果用户没有绑定车辆，自动为其绑定第一辆车的ID
        if (!userVehicleId && vehicleDataList.length > 0) {
          // 获取第一个车辆ID
          userVehicleId = vehicleDataList[0].vehicleId;
          userVehicleBindings[userData.id] = userVehicleId;
          localStorage.setItem('userVehicleBindings', JSON.stringify(userVehicleBindings));
        }
        
        // 筛选出该车辆的所有数据
        const vehicleDataForUser = vehicleDataList.filter(data => data.vehicleId === userVehicleId);
        if (!vehicleDataForUser.length) return null;
        
        // 获取最新的车辆数据记录
        const latestVehicleData = vehicleDataForUser.sort((a, b) => 
          new Date(b.timestamp) - new Date(a.timestamp)
        )[0];
        
        // 获取该车辆的警报信息
        let vehicleAlerts = alertData.filter(a => a.vehicleId === userVehicleId);
        
        // 构建完整的车辆数据对象
        return {
          id: latestVehicleData.vehicleId,
          licensePlate: latestVehicleData.vehiclePlate || '未知车牌号',
          brand: latestVehicleData.vehicleId.includes('1') ? '特斯拉' : 
                 latestVehicleData.vehicleId.includes('2') ? '宝马' : '奔驰',
          model: latestVehicleData.vehicleId.includes('1') ? 'Model 3' : 
                 latestVehicleData.vehicleId.includes('2') ? 'X5' : 'E级',
          year: 2022,
          type: '轿车',
          fuelType: latestVehicleData.vehicleId.includes('1') ? '电动' : '汽油',
          engine: latestVehicleData.vehicleId.includes('1') ? '电动马达' : '内燃机',
          transmission: '自动',
          mileage: Math.floor(Math.random() * 50000) + 5000, // 模拟里程数据
          fuelLevel: latestVehicleData.fuelLevel || Math.floor(Math.random() * 100),
          speed: latestVehicleData.speed || 0,
          temperature: Math.floor(Math.random() * 30) + 60, // 模拟温度数据
          batteryLevel: Math.floor(Math.random() * 50) + 50, // 模拟电池数据
          status: latestVehicleData.emergencyFlag ? 'warning' : 'normal',
          lastUpdated: latestVehicleData.timestamp || new Date().toISOString(),
          lastMaintenance: new Date(Date.now() - 90 * 86400000).toISOString(),
          nextMaintenanceDate: new Date(Date.now() + 90 * 86400000).toISOString(),
          nextMaintenanceMileage: 15000,
          location: {
            address: '北京市海淀区科技园区'
          },
          alerts: vehicleAlerts.map(alert => ({
            id: alert.id,
            type: alert.type,
            severity: alert.severity,
            status: alert.status,
            time: alert.time
          }))
        };
      }
      
      // 如果没有真实数据，回退到本地存储的模拟数据
      // 获取用户车辆绑定关系
      let userVehicleBindings = JSON.parse(localStorage.getItem('userVehicleBindings') || '{}');
      let mockVehicles = JSON.parse(localStorage.getItem('mockVehicles') || '[]');
      let mockAlerts = JSON.parse(localStorage.getItem('mockAlerts') || '[]');
      
      // 获取用户绑定的车辆ID
      let userVehicleId = userVehicleBindings[userData.id];
      
      // 如果用户没有绑定车辆，自动为其绑定第一辆车
      if (!userVehicleId && mockVehicles.length > 0) {
        userVehicleId = mockVehicles[0].id;
        userVehicleBindings[userData.id] = userVehicleId;
        localStorage.setItem('userVehicleBindings', JSON.stringify(userVehicleBindings));
      }
      
      // 获取用户绑定的车辆基本信息
      let vehicle = mockVehicles.find(v => v.id === userVehicleId);
      if (!vehicle && mockVehicles.length > 0) {
        // 如果找不到绑定的车辆，使用第一辆车
        vehicle = mockVehicles[0];
      }
      if (!vehicle) return null;
      
      // 获取该车辆的警报信息
      let vehicleAlerts = mockAlerts.filter(a => a.vehicleId === userVehicleId);
      
      // 构建完整的车辆数据对象
      return {
        id: vehicle.id,
        licensePlate: vehicle.licensePlate,
        brand: vehicle.model?.split(' ')[0] || '未知',
        model: vehicle.model?.split(' ')[1] || vehicle.model,
        year: vehicle.year,
        type: '轿车', // 这里简化处理，实际应该从车辆数据中获取
        fuelType: vehicle.model?.includes('特斯拉') ? '电动' : '汽油',
        engine: vehicle.model?.includes('特斯拉') ? '电动马达' : '内燃机',
        transmission: '自动',
        mileage: Math.floor(Math.random() * 50000) + 5000,
        fuelLevel: Math.floor(Math.random() * 100),
        speed: 0,
        temperature: Math.floor(Math.random() * 30) + 60,
        batteryLevel: Math.floor(Math.random() * 50) + 50,
        status: vehicle.status === 'WARNING' ? 'warning' : 'normal',
        lastUpdated: vehicle.lastUpdated || new Date().toISOString(),
        lastMaintenance: new Date(Date.now() - 90 * 86400000).toISOString(),
        nextMaintenanceDate: new Date(Date.now() + 90 * 86400000).toISOString(),
        nextMaintenanceMileage: 15000,
        location: {
          address: vehicle.location || '未知位置'
        },
        alerts: vehicleAlerts.map(alert => ({
          id: alert.id,
          type: alert.type,
          severity: alert.severity === '高' ? 'high' : alert.severity === '中' ? 'medium' : 'low',
          status: alert.status === 'RESOLVED' ? 'resolved' : 'active',
          time: alert.timestamp
        }))
      };
    } catch (error) {
      console.error('获取用户绑定车辆数据失败:', error);
      return null;
    }
  };
  
  // 获取当前用户绑定的车辆数据
  const vehicleData = getUserBoundVehicleData();

  return (
    <Box sx={{ p: 3 }}>
      {/* 欢迎信息 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          欢迎, {userData?.email || '用户'}
        </Typography>
        <Typography variant="body2" color="textSecondary">
          最后更新: {vehicleData ? formatTimestamp(vehicleData.lastUpdated) : '--'}
        </Typography>
      </div>

      {loading ? (
        <Typography variant="body1">加载数据中...</Typography>
      ) : error ? (
        <Typography variant="body1" color="error">{error}</Typography>
      ) : vehicleData ? (
        <>
          {/* 车辆基本信息卡片 */}
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <div>
                  <Typography variant="h5" gutterBottom>
                    {vehicleData.licensePlate}
                  </Typography>
                  <Typography variant="subtitle1">
                    {vehicleData.brand} {vehicleData.model} ({vehicleData.year})
                  </Typography>
                </div>
                <Chip 
                  label={vehicleData.status === 'normal' ? '正常' : vehicleData.status === 'warning' ? '警告' : '故障'}
                  sx={getStatusStyle(vehicleData.status)}
                />
              </div>
              
              {/* 车辆关键信息指标 */}
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6} md={3}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="textSecondary">里程数</Typography>
                      <Typography variant="h6">{vehicleData.mileage.toLocaleString()} km</Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={12} sm={6} md={3}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="textSecondary">燃油/电量</Typography>
                      <Typography variant="h6">{vehicleData.fuelLevel}%</Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={12} sm={6} md={3}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="textSecondary">当前速度</Typography>
                      <Typography variant="h6">{vehicleData.speed} km/h</Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={12} sm={6} md={3}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="textSecondary">发动机温度</Typography>
                      <Typography variant="h6">{vehicleData.temperature}°C</Typography>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>
            </CardContent>
          </Card>

          {/* 车辆详细信息区域 */}
          <Grid container spacing={3}>
            {/* 左侧 - 车辆静态数据 */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>车辆静态数据</Typography>
                  
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                    <div>
                      <Typography variant="body2" color="textSecondary">车辆类型</Typography>
                      <Typography variant="body1">{vehicleData.type}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">燃油类型</Typography>
                      <Typography variant="body1">{vehicleData.fuelType}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">发动机</Typography>
                      <Typography variant="body1">{vehicleData.engine}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">变速箱</Typography>
                      <Typography variant="body1">{vehicleData.transmission}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">上次保养</Typography>
                      <Typography variant="body1">{formatTimestamp(vehicleData.lastMaintenance)}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">下次保养</Typography>
                      <Typography variant="body1">{formatTimestamp(vehicleData.nextMaintenanceDate)}</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">下次保养里程</Typography>
                      <Typography variant="body1">{vehicleData.nextMaintenanceMileage} km</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">剩余保养里程</Typography>
                      <Typography variant="body1">{vehicleData.nextMaintenanceMileage - vehicleData.mileage} km</Typography>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </Grid>

            {/* 右侧 - 实时数据和位置 */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>车辆实时状态</Typography>
                  
                  <div style={{ marginBottom: 16 }}>
                    <Typography variant="subtitle2" gutterBottom>当前位置</Typography>
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                      <LocationOn color="primary" size={18} style={{ marginRight: 8 }} />
                      <Typography variant="body2">{vehicleData.location.address}</Typography>
                    </div>
                    <div style={{ height: 200, border: '1px solid #e0e0e0', borderRadius: 4 }}>
                      {/* 简化的地图展示 */}
                      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', color: 'text.secondary' }}>
                        <LocationOn size={48} color="primary" />
                      </div>
                    </div>
                  </div>

                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                    <div>
                      <Typography variant="body2" color="textSecondary">电池电量</Typography>
                      <Typography variant="body1">{vehicleData.batteryLevel}%</Typography>
                    </div>
                    <div>
                      <Typography variant="body2" color="textSecondary">胎压状态</Typography>
                      <Typography variant="body1">正常</Typography>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </Grid>

            {/* 底部 - 警告信息 */}
            <Grid item xs={12}>
              <Card>
                <CardContent>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                    <Typography variant="h6">当前警告信息</Typography>
                    <Typography variant="caption" color="textSecondary">
                      {vehicleData.alerts.length} 个警告
                    </Typography>
                  </div>
                  
                  {vehicleData.alerts.length === 0 ? (
                    <Typography variant="body2" color="textSecondary" align="center">
                      暂无警告信息
                    </Typography>
                  ) : (
                    <div style={{ maxHeight: 300, overflowY: 'auto' }}>
                      {vehicleData.alerts.map(alert => (
                        <div key={alert.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid #f0f0f0', minHeight: 60 }}>
                          <div style={{ flex: 1, marginRight: 16, minWidth: 0 }}>
                            <Typography variant="body1" sx={getAlertSeverityStyle(alert.severity)} style={{ wordBreak: 'break-word' }}>
                              {alert.type}
                            </Typography>
                            <Typography variant="caption" color="textSecondary" style={{ display: 'block', wordBreak: 'break-word' }}>
                              {formatTimestamp(alert.time)}
                            </Typography>
                          </div>
                          <Chip 
                            label={alert.status === 'resolved' ? '已解决' : '未解决'}
                            size="small"
                            sx={{ backgroundColor: alert.status === 'resolved' ? 'success.light' : 'error.light', flexShrink: 0 }}
                          />
                        </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </>
      ) : (
        <Typography variant="body1" align="center">暂无车辆数据</Typography>
      )}
    </Box>
  );
};

export default Dashboard;